package com.sdruixinggroup.mondayb2b.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.adapter.HotHomeAdapter;
import com.sdruixinggroup.mondayb2b.adapter.MultiplePagerAdapter;
import com.sdruixinggroup.mondayb2b.adapter.QuickAdapter;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.HomeBeen;
import com.sdruixinggroup.mondayb2b.models.OpenAreas;
import com.sdruixinggroup.mondayb2b.ui.Activities.CityListActivity;
import com.sdruixinggroup.mondayb2b.utils.UserDate;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.sdruixinggroup.mondayb2b.widget.NearbyStoreView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoaderInterface;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import www.library.PullToRefreshBase;
import www.library.PullToRefreshMyScrollView;

import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.AREA_CODE;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME_ERROR;

/**
 * Created by tangjie on 2017/11/9.
 */

public class HomeActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.ll_choice_address)
    LinearLayout llChoiceAddress;
    @BindView(R.id.topbar_title)
    TextView topbarTitle;
    @BindView(R.id.topbar_right)
    TextView topbarRight;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.horizon_pager)
    ViewPager horizonPager;
    @BindView(R.id.ll_page_parent)
    LinearLayout llPageParent;
    @BindView(R.id.home_rich)
    LinearLayout homeRich;
    @BindView(R.id.home_used)
    LinearLayout homeUsed;
    @BindView(R.id.home_raffle)
    LinearLayout homeRaffle;
    @BindView(R.id.more_shops)
    TextView moreShops;
    @BindView(R.id.ll_nearby_shops)
    LinearLayout llNearbyShops;
    @BindView(R.id.hot_recyclerview)
    RecyclerView hotRecyclerview;
    @BindView(R.id.tv_special_goods_more)
    TextView tvSpecialGoodsMore;
    @BindView(R.id.scrollView)
    PullToRefreshMyScrollView scrollView;
    private TextView more_shops;
    private LinearLayout home_raffle, home_rich, home_used;
    private Intent intent;
    private TextView topbar_center;
    private List<String> banners;
    private OpenAreas.AreasBean areasBean;
    private MultiplePagerAdapter multiplePagerAdapter;
    private List<HomeBeen.SpecialOfferBean> specialOfferBeen = new ArrayList<>();
    private List<Object> hotGoods;
    private HotHomeAdapter hotHomeAdapter;
    private AMapLocation amapLocation;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object resp) {/* Do something */
        if (resp instanceof OpenAreas.AreasBean) {
            areasBean = (OpenAreas.AreasBean) resp;
            tvAddress.setText(areasBean.getName());
            AREA_CODE = areasBean.getId();
            UserInfoUtil.AREA_CODE_NAME = areasBean.getName();
            UserDate.setAreaName(getApplicationContext(), areasBean.getName());
            UserDate.setAreaID(getApplicationContext(), areasBean.getId());

            queryHomeData(amapLocation.getLongitude(), amapLocation.getLatitude());
        }

    }


    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    private AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            // TODO Auto-generated method stub
            if (amapLocation != null) {
                HomeActivity.this.amapLocation = amapLocation;
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    double locationType = amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    double latitude = amapLocation.getLatitude();//获取纬度
                    UserInfoUtil.mLatitude = amapLocation.getLatitude();
                    UserInfoUtil.mLongitude = amapLocation.getLongitude();
                    if (HomeActivity.this.response == null) {
                        queryAreaData(amapLocation.getLongitude(), amapLocation.getLatitude());
                        queryHomeData(amapLocation.getLongitude(), amapLocation.getLatitude());
                    }

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //声明AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    private HomeBeen response;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);

        AREA_CODE = UserDate.getAreaID(getApplicationContext());
        UserInfoUtil.AREA_CODE_NAME = UserDate.getAreaName(getApplicationContext());

        tvAddress.setText(UserInfoUtil.AREA_CODE_NAME);
        initLocation();
        EventBus.getDefault().register(this);

        hotGoods = new ArrayList<>();

        intent = new Intent(this, WebActivity.class);
        more_shops = (TextView) findViewById(R.id.more_shops);
        more_shops.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeActivity.this, MoreShopsActivity.class));
            }
        });
        home_raffle = (LinearLayout) findViewById(R.id.home_raffle);
        home_rich = (LinearLayout) findViewById(R.id.home_rich);
        home_used = (LinearLayout) findViewById(R.id.home_used);

        topbar_center = (TextView) findViewById(R.id.topbar_title);
        topbar_center.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //startActivity(new Intent(HomeActivity.this, SearchActivity.class));
                if (null != HomeActivity.this.amapLocation) {
                    String parms = "search?" + "&area_id=" + UserInfoUtil.AREA_CODE + "&latitude=" + amapLocation.getLatitude()
                            + "&longitude=" + amapLocation.getLongitude();
                    toWebView(parms);
                }

            }
        });
        findViewById(R.id.topbar_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeActivity.this, CheckActivity.class));
            }
        });

        home_raffle.setOnClickListener(this);
        home_used.setOnClickListener(this);
        home_rich.setOnClickListener(this);
        //设置banner样式
        banners = new ArrayList<>();
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.ZoomOutSlide);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                List<HomeBeen.Banner> banners = response.getBanners();
                if (null != banners) {
                    HomeBeen.Banner banner = banners.get(position);
                    Intent intent = new Intent(getBaseContext(), WebActivity.class);
                    intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, banner.getUrl());
                    intent.putExtra("isbanner", true);
                    startActivity(intent);
                }
            }
        });
        banner.setImageLoader(new ImageLoderImp());
      /*  banner.setImages(banners);
        banner.start();*/
        starBanner();
        multiplePagerAdapter = new MultiplePagerAdapter(specialOfferBeen, getApplicationContext());
        horizonPager.setAdapter(multiplePagerAdapter);
        multiplePagerAdapter.setOnItemClickListener(new MultiplePagerAdapter.OnItemClickListener() {
            @Override
            public void listener(HomeBeen.SpecialOfferBean specialOfferBean) {
                String params = "productdetail" + "?goods_id=" + specialOfferBean.getGoods_id() + "&" + "area_id=" + UserInfoUtil.AREA_CODE + "&latitude=" + amapLocation.getLatitude()
                        + "&longitude=" + amapLocation.getLongitude();
                toWebView(params);
            }
        });
        horizonPager.setOffscreenPageLimit(5);
        horizonPager.setPageMargin((int) getResources().getDimension(R.dimen.dimen_12));
        llPageParent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return horizonPager.dispatchTouchEvent(event);
            }
        });
        hotHomeAdapter = new HotHomeAdapter(getApplicationContext());
        hotHomeAdapter.setData(hotGoods);
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object object = hotGoods.get(position);
                if (object instanceof Integer) {
                    return gridLayoutManager.getSpanCount();    // 头部和尾部 特殊处理
                } else {
                    return 1;
                }

            }
        });
        hotRecyclerview.setNestedScrollingEnabled(false);
        hotRecyclerview.setAdapter(hotHomeAdapter);
        hotRecyclerview.setLayoutManager(gridLayoutManager);
        hotRecyclerview.setHasFixedSize(false);
        hotRecyclerview.setFocusable(false);
        hotHomeAdapter.setOnItemClickListener(new QuickAdapter.OnItemClickListener<Object>() {
            @Override
            public void OnItemClick(Object itemData, int postion) {
                if (null != amapLocation) {

                    if (itemData instanceof HomeBeen.HotBean) {
                        HomeBeen.HotBean bean = (HomeBeen.HotBean) itemData;
                        String params = "productdetail" + "?goods_id=" + bean.getGoods_id() + "&area_id=" + UserInfoUtil.AREA_CODE + "&latitude=" + amapLocation.getLatitude()
                                + "&longitude=" + amapLocation.getLongitude();
                        toWebView(params);
                    } else if (itemData instanceof HomeBeen.RecommendBean) {
                        HomeBeen.RecommendBean bean = (HomeBeen.RecommendBean) itemData;
                        String params = "productdetail" + "?goods_id=" + bean.getGoods_id() + "&area_id=" + UserInfoUtil.AREA_CODE + "&latitude=" + amapLocation.getLatitude()
                                + "&longitude=" + amapLocation.getLongitude();
                        toWebView(params);
                    }

                }

            }
        });

       // scrollView.setSmoothScrollingEnabled(true);
        scrollView.getRefreshableView().fling(600);
        scrollView.getRefreshableView().setSmoothScrollingEnabled(true);
        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2(){
            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                queryHomeData(amapLocation.getLongitude(), amapLocation.getLatitude());
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {


            }
        });

    }

    @Override
    public void onClick(View view) {
        if (view == home_raffle) {
            intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, "lottery?");
            startActivity(intent);
        }
        if (view == home_rich) {
            intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, "wealth?");
            startActivity(intent);
        }
        if (view == home_used) {
            intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, "howuse?");
            startActivity(intent);
        }
    }

    @OnClick(R.id.ll_choice_address)
    public void onClick() {
        Intent intent = new Intent(getBaseContext(), CityListActivity.class).putExtra("type",1);
        startActivity(intent);
    }

    @OnClick(R.id.tv_special_goods_more)
    public void onClickSpecialGoodsMore() {
        if (null != amapLocation) {
            String params = "linelist?special_offer=1" + "&area_id=" + UserInfoUtil.AREA_CODE + "&latitude=" + amapLocation.getLatitude()
                    + "&longitude=" + amapLocation.getLongitude();
            toWebView(params);
        }
    }


    private class ImageLoderImp implements ImageLoaderInterface<ImageView> {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Picasso 加载图片简单用法

            String url = String.valueOf(path);
            Log.e("HQQ", "url:  " + url);
            Glide.with(context)
                    .load(url)
                    //  .centerCrop()
                    //   .placeholder(R.mipmap.place_holder_dark)
                    .error(R.drawable.home_banner)
                    // .crossFade()
                    .into(imageView);

        }


        @Override
        public ImageView createImageView(Context context) {
            ImageView imageView = new ImageView(context);
            return imageView;
        }
    }

    //开始轮播
    public void starBanner() {
        if (null != banner) {
            banner.start();
        }
    }

    //结束轮播
    public void stopBanner() {
        if (null != banner) {
            banner.stopAutoPlay();
        }
    }


    public void updataBanner(List<String> images) {

        if (null != banner) {
           // this.banners.clear();
            if(banners.isEmpty()){
                banners.addAll(images);
                banner.update(banners);
            }

        }

    }


    private void queryHomeData(double longitude, double latitude) {
        String url = API.MEMBER_INDEX + "longitude=" + longitude + "&latitude=" + latitude + "&area_id=" + UserInfoUtil.AREA_CODE + "&access_token=" + UserInfoUtil.getInfoToken(getApplicationContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<HomeBeen> typeToken = new TypeToken<HomeBeen>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<HomeBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

                if(null != scrollView){
                    scrollView.onRefreshComplete();
                }
            }

            @Override
            public void onResponse(HomeBeen response, int id) {


                if (null != response) {
                    if (response.getErr_code() == 0) {
                        HomeActivity.this.response = response;
                        List<HomeBeen.Banner> banners = response.getBanners();
                        if (null != banners && !banners.isEmpty()) {
                            List<String> temps = new ArrayList<>();
                            for (HomeBeen.Banner banner : banners) {
                                temps.add(banner.getPic());
                            }
                            updataBanner(temps);
                            banner.setVisibility(View.VISIBLE);
                           // starBanner();
                        } else {
                            banner.setVisibility(View.GONE);
                        }
                        List<HomeBeen.MerchantsBean> merchantsBeans = response.getMerchants();
                        llNearbyShops.removeAllViews();

                        if (null != merchantsBeans && !merchantsBeans.isEmpty()) {
                            for (HomeBeen.MerchantsBean bean : merchantsBeans) {
                                NearbyStoreView nearbyStoreView = new NearbyStoreView(getApplicationContext());
                                nearbyStoreView.setData(bean);
                                llNearbyShops.addView(nearbyStoreView);
                            }
                            llNearbyShops.setVisibility(View.VISIBLE);
                        } else {
                            llNearbyShops.setVisibility(View.GONE);
                        }

                        List<HomeBeen.SpecialOfferBean> specialOfferBean = response.getSpecial_offer();
                        if (null != specialOfferBean && !specialOfferBean.isEmpty()) {
                            multiplePagerAdapter.reflushData(specialOfferBean);
                            llPageParent.setVisibility(View.VISIBLE);
                            horizonPager.setAdapter(multiplePagerAdapter);
                        } else {
                            llPageParent.setVisibility(View.GONE);
                        }

                        List<HomeBeen.HotBean> hotBeans = response.getHot();
                        hotGoods.clear();
                        if (hotBeans != null && !hotBeans.isEmpty()) {
                            hotGoods.addAll(hotBeans);
                        }
                        hotGoods.add(HotHomeAdapter.HEADER_VIEW_TYPE);
                        List<HomeBeen.RecommendBean> recommendBeans = response.getRecommend();
                        if (null != recommendBeans && !recommendBeans.isEmpty()) {
                            hotGoods.addAll(recommendBeans);
                        }
                        hotHomeAdapter.reflashData(hotGoods);
                    } else if (response.getErr_code() == TOKEN_OUT_TIME || response.getErr_code() == TOKEN_OUT_TIME_ERROR) {
                        UserInfoUtil.intoLogin(HomeActivity.this);
                    } else {
                        showToast(response.getErr_msg());
                    }
                }

                if(null != scrollView){
                    scrollView.onRefreshComplete();
                }


            }
        });
    }

    private void initLocation() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);


        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

        /**
         * 获取一次定位
         */
        //该方法默认为false，true表示只定位一次
        mLocationOption.setOnceLocation(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();
    }

    private void toWebView(String param) {
        Intent intent = new Intent(getBaseContext(), WebActivity.class);
        intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, param);
        startActivity(intent);
    }

    private void queryAreaData(double longitude, double latitude) {


        String url = API.AREAS + UserInfoUtil.getInfoToken(this) + "&longitude=" + longitude + "&latitude=" + latitude;
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<OpenAreas> typeToken = new TypeToken<OpenAreas>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<OpenAreas>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(OpenAreas response, int id) {


                if (null != response) {
                    if (response.getErr_code() == 0) {
                        OpenAreas.AreasBean areasBean = response.getArea();
                        if (null != areasBean) {
                            tvAddress.setText(areasBean.getName());
                            AREA_CODE = areasBean.getId();
                            UserDate.setAreaName(getApplicationContext(), areasBean.getName());
                            UserDate.setAreaID(getApplicationContext(), areasBean.getId());
                        } else {
                            if (TextUtils.isEmpty(UserDate.getAreaName(getApplicationContext()))) {
                                Intent intent = new Intent(getBaseContext(), CityListActivity.class).putExtra("type",1);
                                startActivity(intent);
                            }
                        }
                    }
                }

            }
        });

    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
